#include <arpa/inet.h>
#include <netinet/in.h>
#include <stdio.h>
#include <string.h>
#include <sys/socket.h>
#include <unistd.h>

int main(int argc, char const* argv[])
{
    int socketfd, confd, n;
    socklen_t len;
    struct sockaddr_in servaddr, cliaddr;
    char buf[256];

    //创建套接字
    socketfd = socket(AF_INET, SOCK_STREAM, IPPROTO_TCP);
    if (socketfd < 0) {
        printf("[SERVER] create socket failed.\n");
        return -1;
    }

    // 绑定
    bzero(&servaddr, sizeof(servaddr));
    servaddr.sin_family = AF_INET;
    servaddr.sin_addr.s_addr = htonl(INADDR_ANY);
    servaddr.sin_port = htons(8000);
    if (bind(socketfd, (struct sockaddr*)&servaddr, sizeof(servaddr)) < 0) {
        printf("[SERVER] bind error.\n");
        return -1;
    }

    // listen
    if (listen(socketfd, 10) < 0) {
        printf("[SERVER] listen failed.\n");
        return -1;
    }

    // wait connect
    while (1) {
        len = sizeof(cliaddr);
        confd = accept(socketfd, (struct sockaddr*)&cliaddr, &len);
        if (confd < 0) {
            printf("[SERVER] accept failed.\n");
            return -1;
        } else {
            printf("[SERVER] connection from %s:%d\n",
                inet_ntop(AF_INET, &cliaddr.sin_addr, buf, sizeof(buf)),
                ntohs(cliaddr.sin_port));
        }

        n = recv(confd, buf, sizeof(buf), 0);
        if (n > 0) {
            buf[n] = '\0';
            printf("[SERVER] received msg: %s\n", buf);
            
            strcpy(buf, "Hello from server");
            send(confd, buf, sizeof(buf), 0);
            close(confd);
        }
    }

    return 0;
}
